package engine.newUi
{
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.View;
	import engine.data.ViewObject;
	import engine.event.SoundEvent;
	import engine.flag.ResourcesPath;
	import engine.logic.DoubleClickManager;
	import engine.logic.LogSendLogic;
	import engine.logic.McPool;
	import engine.logic.MenuListManager;
	import engine.logic.event.LogicEvent;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.scene.SceneManager;
	import engine.tip.TipsMainLogic;
	import engine.ui.AlertUI;
	
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	
	import newx.BaseObject;
	import newx.com.ResManager;
	import newx.com.config.StaticIni;
	import newx.com.control.NxClip;
	import newx.com.control.tab.NxTabEvent;
	import newx.com.control.text.NxLabel;
	import newx.com.control.window.NxWindowEvent;
	import newx.utils.MouseHandle;

	/**
	 * 仓库逻辑 
	 * @author liuel
	 * 
	 */
	public class DepositoryLogic
	{
		private static var _self:DepositoryLogic;
		private var _model     :ModelLocator;
		
		private var _bindManage:BindManage;
		
		public var ui         :DepotUI;
		
		private var _bindToolIndex  :int =	-1;
		private var _bindToolIndex1 :int =-1;
		
		/**仓库中格子数目**/
		private var _gridMax        :int ;
		private var _itemWidth      :int = 40;
		private var _itemHeight     :int = 40;
				
		/**当前开启的格子数**/
		private var _currNum        :uint= 0;
		/**仓库中格子数组**/
		private var _guidallarr    :Array =[];
		
		/**仓库中格子是否开启**/
		private var _gridIsOpen     :Array=[];
		
		/**物品数组**/
		private var itemarr         :Array=[];
		
		private var itemMC          :MovieClip;
		private var img             :NxClip=null ;
		private var txtCount        :NxLabel;
		
		
		private var _doubleClickManager	: 	DoubleClickManager;
		private var mc				:MovieClip;
		private var mc1			:MovieClip;
		private var _mouse			:MouseHandle;
		/**
		 *当前页数 
		 */		
		private var _currentPage	:int=1;
		private var _one_page_max:int;
		//存放遮罩的数组
		private var _veilArr:Array=[];
		/**
		 * Group状态
		 * BASIV_STATE	普通状态
		 * ROLL_STATE   滑动状态
		 * DISUSE_STATE 不能用状态
		 */		
		private const BASIV_STATE			:int	= 1;
		private const 	ROLL_STATE          :int	= 2;
		private const 	DISUSE_STATE		:int	= 3;
		/**选中状态**/
		private const SELE_STATE			:int	= 4;
		public static function getInstance():DepositoryLogic
		{
			if(_self == null)
			{
				_self =new DepositoryLogic();
			}
			return _self;
		}
		public function DepositoryLogic()
		{
			
		}
		 public function  Init():void
		{
			_mouse	= MouseHandle.getInstance();
			 ui     = DepotUI.getInstance();
			_bindManage=BindManage.getInstance();
			_model = ModelLocator.getInstance();
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_OPEN_STORE_BOX),onOpen);
			ui.page.dataProvider=[{label:"1",data:1},{label:"2",data:2}];
			_one_page_max	= ui.gridGroup.row * ui.gridGroup.col;
			_gridMax=_one_page_max*ui.page.dataProvider.length;
			infoUI();
			 _doubleClickManager = DoubleClickManager.getInstance();
			 _doubleClickManager.addDoubleClick(DepositoryLogic,singleClick, doubleClick );
			 _veilArr =["custSkin_45","custSkin_46","custSkin_47","custSkin_48","custSkin_49"];
		}
		
		 public function	BeforeShow():void
		{
			 clearImg();
			 if(!SceneManager._itemIconLoad)
			 {
				 _model.addEventListener(LogicEvent.ITEMICONLOADED,loaded);
				 function loaded():void
				 {
					 _bindToolIndex1 = -1
					 _bindToolIndex=-1;
					 BeforeShow();
					 _model.removeEventListener(LogicEvent.ITEMICONLOADED,loaded)
				 }
			 }
			 if(_bindToolIndex1 == -1)
			 {
				 _bindToolIndex1 = _bindManage.BindProp(_model.scene.GetView(View.VIEWPORT_STORE),"ExpandStoreBoxCap",this,"level")
			 }
			//绑定数据
			if( _bindToolIndex == -1 )
			{
				_bindToolIndex = _bindManage.BindView(_model.scene,View.VIEWPORT_STORE,onDePositItem,onTakeItem);
				
			}
		 
			addListener();
		}
		public function	AfterHide():void
		{
			if(_bindToolIndex1 !=-1)
			{
				_bindManage.UnbindProp(_model.scene.Role,"ExpandStoreBoxCap",_bindToolIndex1);
			}
			//解绑
			if(_bindToolIndex != -1)
			{
				_bindToolIndex = _bindManage.UnbindView(View.VIEWPORT_STORE,_bindToolIndex);
			    
			}
	
			
			_bindToolIndex = -1;
			_bindToolIndex1 =-1;
			removeListener();
			clearImg();
			
		}
		private function infoUI():void
		{
//			ui.lab_open.glowColor = 0x
			ui.gridGroup.buttonMode = true;
			for(var i:int=0;i<this._one_page_max;i++)
			{
			    img = new NxClip();
				img.isCache = true;
			    txtCount=	new NxLabel();
				itemMC = ui.gridGroup.getItemByIndex(i);
				
				if(i<this._currNum)
				{
					this._gridIsOpen[i] = true;
					itemMC.gotoAndStop(1);
				}
				else
				{
					this._gridIsOpen[i] = false;
					
					
					img.isCache = true;
					img.width   = _itemWidth;
					img.height  = _itemHeight;
					img.x =	img.y   = 4;
					img.source  = "";
					itemMC.gotoAndStop(3);
					
				}
					txtCount.color=0xffffff;
					txtCount.glowColor = 0x081f22;
				    txtCount.htmlText = "";
				    itemMC["img"]=img ;
					itemMC["img"].x =itemMC["img"].y =4;
					itemMC["index"]=i+1
				
					itemMC["txtCount"]=txtCount;
					itemMC["txtCount"].x =27;
					itemMC["txtCount"].y =25;
					itemMC.addChild(img);
					
					itemMC.addChild(txtCount);
				   _guidallarr.push(itemMC);
		}
	   }
		private function  clearImg():void
		{
			for(var i:int=0;i<this._one_page_max;i++)
			{
				itemMC = ui.gridGroup.getItemByIndex(i);
				if(itemMC["txtCount"])
					itemMC["txtCount"].text ="";
				if(itemMC["data"])
				{
					itemMC["data"][_currentPage]=null;
				}
				removeVeil(itemMC);
				img=itemMC["img"] ; 
				if(img)
					img.source ="";
				
			}
		}
		private function addListener():void
		{
			ui.windowBG.addEventListener(NxWindowEvent.WINDOW_CLOSE,onClickClose);
			ui.btnExpandDepot.addEventListener(MouseEvent.CLICK,onExpandDepot_Click);
			ui.btnOrder .addEventListener(MouseEvent.CLICK,btnOrder_Click);
			ui.gridGroup.addItemsEvent(MouseEvent.ROLL_OVER,onItemOver);
			ui.gridGroup.addItemsEvent(MouseEvent.ROLL_OUT,onItemOut);
			ui.gridGroup.addItemsEvent(MouseEvent.CLICK,onClick_Take);
			ui.gridGroup.addEventListener(MouseEvent.CLICK,onClick_Open,true);
			ui.page.addEventListener(NxTabEvent.TAB_CLICK,tabClickHandle);
		}
		private function tabClickHandle(e:NxTabEvent):void
		{
			_currentPage=e.item.data;
			clearImg();
			refreshCurrentPage();
		}
		private function refreshCurrentPage():void
		{
			var view:Object=_model.scene.GetView(View.VIEWPORT_STORE).Properties;
			level=_currNum;
			for (var i:int =1; i <=_one_page_max; i++) 
			{
				var j:int=i+(_currentPage-1)*_one_page_max;
				updataItemImage(view.hasOwnProperty(j)?view[j]:j,view.hasOwnProperty(j));
			}
		}
		private function removeListener():void
		{
			ui.windowBG.removeEventListener(NxWindowEvent.WINDOW_CLOSE,onClickClose);
			ui.btnExpandDepot.removeEventListener(MouseEvent.CLICK,onExpandDepot_Click);
			ui.btnOrder.removeEventListener(MouseEvent.CLICK,btnOrder_Click);
			ui.gridGroup.removeItemsEvent(MouseEvent.ROLL_OVER,onItemOver);
			ui.gridGroup.removeItemsEvent(MouseEvent.ROLL_OUT,onItemOut);
			ui.gridGroup.removeItemsEvent(MouseEvent.CLICK,onClick_Take);
			ui.gridGroup.removeEventListener(MouseEvent.CLICK,onClick_Open,true);
			
		}
		private function singleClick(e:MouseEvent):void
		{
			itemMC =e.currentTarget as MovieClip
			var dataObj : Object = itemMC[ "data" ];
			if( null != dataObj &&dataObj[_currentPage])
			{
				MenuListManager.clickItem( DepositoryLogic, dataObj[_currentPage] );
			}
			if(mc)
			{
				if(itemMC.currentFrame ==DISUSE_STATE ||itemMC.currentFrame == SELE_STATE)
					return;
				if(itemMC.currentFrame != ROLL_STATE)
				{
					itemMC.gotoAndStop(ROLL_STATE);
				}
				
			}
			else
			{
				if(itemMC.currentFrame ==DISUSE_STATE || itemMC.currentFrame == SELE_STATE)
					return;
				itemMC.gotoAndStop(ROLL_STATE);
			}
			mc = itemMC;
		}
		private function doubleClick(e:MouseEvent):void
		{
			itemMC =e.currentTarget as MovieClip
			var data:Object= itemMC[ "data" ];
			if(!data)return 
			var dataObj : ViewObject =data[_currentPage]
			if(dataObj ==null)
				return;
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_MOVEITEM,
				View.VIEWPORT_STORE, int( dataObj.ObjKey ),
				View.VIEWPORT_TOOL, 0);
		}
		/**
		 * 更新图片显示 
		 * @param oper true 存 false 取
		 * @param itemObject
		 * 
		 */
		private function updataItemImage(itemObject:*,oper:Boolean):void
		{
			//道具位置
			var itemPos:int	=itemObject is ViewObject?uint(itemObject.ObjKey):itemObject;
//			trace("DepositoryLogic.updataItemImage(itemObject, oper)",itemPos,oper);
//			oper?addItemImage(itemObject,itemPos):removeItemImage(itemObject,itemPos);
			oper?addItemImage(itemObject,itemPos):removeItemImage(itemObject,itemPos);
		}
		/**
		 * 添加道具图片
		 */
		private function addItemImage(itemObject:ViewObject,itemPos:int):void
		{
			var index:int = (itemPos - 1)%_one_page_max; 
			var targetPage:int=((itemPos - 1)/_one_page_max)+1;
			if(targetPage!=_currentPage)
			{
				if(!itemMC["data"])
				{
					itemMC["data"]	=	{};
				}
				itemMC["data"][targetPage]	= itemObject;
				return ;
			}
			itemMC = ui.gridGroup.getItemByIndex(index);
			img=itemMC["img"] ; 
			img.source =ResourcesPath.getPropsURL(itemObject.GetProperties("Photo"));
			if(img.parent==null)
			{
				itemMC.addChild(img);
			}
			//当时有数量的物品时，显示物品
			if(itemObject.CheckProperties("Amount")){
				txtCount=itemMC["txtCount"] ;
				txtCount.htmlStr = itemObject.GetPropertiesEx("Amount");
				if(txtCount.parent==null)
				{
					itemMC.addChild(txtCount);
				}
//				//绑定数量
//				var amountIndex:int	= _bindManage.BindProp(itemObject,"Amount",itemMC["txtCount"],"htmlStrByBorder",backunc);
				var amountIndex	:int	=BindManage.getInstance().BindPropInViewObj(itemObject.parent as View,itemObject.ObjKey,"Amount",BindFunc,null,[itemMC["txtCount"],"htmlStrByBorder",itemObject]);
				itemMC["amountIndex"] = amountIndex;
				itemMC["bindPage"]	=	_currentPage;
			}
			else
			{
				itemMC["txtCount"].htmlStr="";
			}
			if(!itemMC["data"])
			{
				itemMC["data"]	=	{};
			}
			itemMC["data"][targetPage]	= itemObject;
			itemMC.addEventListener(MouseEvent.MOUSE_DOWN,beginDrag);
			if(itemMC["date"])
			{
				removeVeil(itemMC);
			}
			addVeil(itemObject,itemMC);
		}
		public function BindFunc(PropertiesName:String,PropertiesValue:*,pList:Array):void
		{
			var		Obj:NxLabel	=	pList[0];
			var		value:*		=	pList[1];
			var 	itemObject:ViewObject		=	pList[2];
			var 	itemPos:int =uint(itemObject.ObjKey);
			var targetPage:int=((itemPos - 1)/_one_page_max)+1;
			if(targetPage!=_currentPage)
			{
				if(!itemMC["data"])
				{
					itemMC["data"]	=	{};
				}
				itemMC["data"][targetPage]	= itemObject;
				return ;
			}
			var perWidth:int	=	5;
			Obj.x=32-perWidth*(String(PropertiesValue).length-1)
			Obj[value]=PropertiesValue;	
		}
		/**
		 * 删除道具图片
		 */
		private function removeItemImage(itemObject:*,itemPos:int):void
		{
			var index:int = (itemPos - 1)%_one_page_max 
			itemMC=	ui.gridGroup.getItemByIndex(index);
			var targetPage:int = 0 
			if(itemPos<_one_page_max)
			{
				targetPage=int(itemPos/_one_page_max)+1;
			}else if ( itemPos%_one_page_max ==0 )
			{
				targetPage=int(itemPos/_one_page_max)
			}else
			{
				targetPage=int(itemPos/_one_page_max)+1
			}
			if(targetPage==_currentPage)
			{
			(itemMC["img"] as NxClip).source = "";
			itemMC["txtCount"].text = "";
			removeVeil(itemMC);
			}
			//清除绑定
			if(itemMC["amountIndex"]!=null&&itemMC.data&&targetPage==itemMC["bindPage"]){
				_bindManage.UnbindProp(itemMC.data[itemMC["bindPage"]],"Amount",int(itemMC["amountIndex"]));
			}
			if(itemMC["data"])
			itemMC["data"][targetPage] = null;
			itemMC["txt"]	=	null;
			itemMC["amountIndex"]	=null;
			
		}
		/**
		 *添加遮罩 
		 * 
		 */		
		private function addVeil(ViewObj:ViewObject,mc:MovieClip):void
		{
			var color:String =ViewObj.GetProperties("Color");
			var panle:MovieClip = ResManager.newResClass(_veilArr[int(color)-1]) as MovieClip;
			if(panle==null)
				return;
			mc.addChild(panle);
			panle.x=3.5;
			panle.y=4;
			mc["Veil"]=panle;
			mc["date"]=ViewObj;
		}
		/**
		 *删除遮罩 
		 * @param mc
		 * 
		 */		
		private function removeVeil(mc:MovieClip):void
		{
			if(mc["Veil"])
			{
				McPool.returnRes( mc["Veil"].url, mc["Veil"].parent.removeChild(mc["Veil"]));
				mc["Veil"]=null;
				mc["date"]=null;
			}
		}
		////////////////////////////////////////////////////////回调函数//////////////////////////////////////////////////////
		
		/**
		 * 更新新开启格子 删除未开启图片 
		 * @param value 扩充的格子数目
		 * 
		 */		
		public function set level(value:int):void
		{
			//扩充前开启数
			var  val:int=this._currNum;
			//扩充后开启数
			val	=	countIndex(_currNum)
			_currNum	=	24+value;
			ui.lab_open.htmlStr=StaticIni.getSwfLangStrVar("UIString_1000001",[_currNum,_gridMax]);
			_currNum	=	countIndex(_currNum);
	
			var targetIndex:int=_currNum;
			if(val<=_currNum)
			{
				for(var i:int=0;i<_currNum;i++)
				{
					this._gridIsOpen[i] = true;
					itemMC = ui.gridGroup.getItemByIndex(i);
//					(itemMC["img"] as NxClip) .source = "";
//					itemMC["txtCount"].text = "";
					itemMC.gotoAndStop(1);
				}
				for( i=_currNum;i<_one_page_max;i++)
				{
					this._gridIsOpen[i] = false;
					itemMC = ui.gridGroup.getItemByIndex(i);
					(itemMC["img"] as NxClip) .source = "";
					itemMC["txtCount"].text = "";
					itemMC.gotoAndStop(3);
				}
			}
			else if(val==0&&_currNum==0)
			{
				for( i=0;i<_one_page_max;i++)
				{
					this._gridIsOpen[i] = false;
					itemMC = ui.gridGroup.getItemByIndex(i);
					(itemMC["img"] as NxClip) .source = "";
					itemMC["txtCount"].text = "";
					itemMC.gotoAndStop(3);
				}
			}	
			_currNum	=	value;
			function countIndex(ii:int):int
			{
				var targetIndex:int
				if(int(ii/_one_page_max)+1==_currentPage)
				{
					targetIndex=ii%_one_page_max;
				}
				else if(int(ii/_one_page_max)+1>_currentPage)
				{
					targetIndex=_one_page_max
				}
				else 
				{
					targetIndex=0
				}
				return targetIndex;
			}
		}
		
		/**
		 *存物品 
		 * 
		 */		
		private function onDePositItem(propertiesName:String,propertiesValue:ViewObject,data:*):void
		{
			updataItemImage(propertiesValue,true);
		}
		
		/**
		 * 取道具
		 */
		private function onTakeItem(propertiesName:String,propertiesValue:*,data:*):void
		{
			updataItemImage(propertiesValue,false);
		}
		////////////////////////////////////////////////////////监听函数/////////////////////////////////////////////////////
		private function onOpen(e:CustomMsgEvent):void
		{
			ui.showOrHide();
		}
		private function 	onClickClose(e:NxWindowEvent):void
		{
			ui.hide();
		}
		
		/**
		 * 点击开启仓库锁 
		 * @param e
		 * 
		 */
		
		private function onExpandDepot_Click(e:MouseEvent):void
		{
			if(this._currNum>=this._gridMax)
			{
				AlertUI.showAlert(StaticIni.getSwfLangStr("UIStr_1000007"),StaticIni.getSwfLangStr("UIStr_1000549"));
				return;
			}
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_BUY_NEXT_STORE,this._currNum+24+1);
			

		}
		
		/**
		 * 点击整理仓库
		 * @param e
		 * 
		 */		
		private function btnOrder_Click(e:MouseEvent):void
		{
			SystemSender.getInstance().CustomMsg(
				CustomToServerFlag.CLIENT_CUSTOMMSG_ARANGEITEM,
				View.VIEWPORT_STORE,0,0);
			_model.dispatchEvent(new SoundEvent(SoundEvent.PACKET_SORT));
		}
		
		/**
		 * 显示物品Tips 
		 * @param e
		 * 
		 */		
		private function onItemOver(e:MouseEvent):void
		{
			itemMC	=	e.currentTarget as MovieClip;
			var itemObject:Object = itemMC.data ;
			if(itemObject != null)
			{
				TipsMainLogic.instance.showMain(itemObject[_currentPage]);
			}
			if(mc)
			{
				if(itemMC.currentFrame ==DISUSE_STATE)
				{
					itemMC.gotoAndStop(SELE_STATE);
				}
				else if(itemMC.currentFrame !=ROLL_STATE)
				{
					itemMC.gotoAndStop(ROLL_STATE);
				}
			}
			else
			{
				if(itemMC.currentFrame ==DISUSE_STATE)
				{
					itemMC.gotoAndStop(SELE_STATE);
				}
				else
				{
					itemMC.gotoAndStop(ROLL_STATE);
				}
				
			}
		
		}
		private function onItemOut(e:MouseEvent):void
		{
			TipsMainLogic.instance.hide();
			itemMC = e.currentTarget as MovieClip;
			if(itemMC.currentFrame ==SELE_STATE)
			{
				itemMC.gotoAndStop(DISUSE_STATE);
			}
			else if(itemMC.currentFrame ==ROLL_STATE)
			{
				itemMC.gotoAndStop(BASIV_STATE);
			}
			
		}
		private function beginDrag(e:MouseEvent):void
		{
			var mc:MovieClip=e.currentTarget as MovieClip;
			if(mc && mc["img"].content)
			{
//				_mouse.setDrag(mc["img"].content,true,mc["data"]);
				ui.gridGroup.addItemsEvent(MouseEvent.MOUSE_UP,endDrag);
			}  
		}
		/**
		 * 
		 * @param e
		 * 
		 */
		private function endDrag(e:MouseEvent):void
		{
			var mc:MovieClip=e.currentTarget as MovieClip;
			if(mc && mc["data"])
			{
				
			}
			else
			{
				var obj:ViewObject=_mouse.targetData as ViewObject;
				if(obj == null) return;
//				trace("从位置："+obj.ObjKey,"拖到位置："+mc["index"]);
			}
			_mouse.removeDrag();
		}
		/**
		 * 点击取出物品 
		 * @param e
		 * 
		 */		
		private function onClick_Take(e:MouseEvent):void
		{
			_doubleClickManager.onClick(DepositoryLogic,e);
//			itemMC =e.currentTarget as MovieClip
//			var dataObj : ViewObject = itemMC[ "data" ];
//			if( null != dataObj )
//			{
//				MenuListManager.clickItem( DepositoryLogic, dataObj );
//			}
//			if(mc)
//			{
//				if(itemMC.currentFrame ==DISUSE_STATE)
//					return;
//				if(itemMC.currentFrame != ROLL_STATE)
//				{
//					itemMC.gotoAndStop(ROLL_STATE);
//				}
//				
//			}
//			else
//			{
//				if(itemMC.currentFrame ==DISUSE_STATE)
//					return;
//				itemMC.gotoAndStop(ROLL_STATE);
//			}
//			mc = itemMC;
		}
		/**
		 * 点击未开启的格子 
		 * @param e
		 * 
		 */		
		private function onClick_Open(e:MouseEvent):void
		{
			var clicp:MovieClip=e.target as MovieClip
			if(clicp)
				var currInde:int=this._guidallarr.indexOf(clicp);
			
			if(_gridIsOpen[currInde] == false)
			{
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_BUY_NEXT_STORE,currInde+1+_one_page_max*(_currentPage-1));

			}
			LogSendLogic.getInstance().btnClickNumSend(22806)
		}
	}
}